<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>操作系统学习笔记-信号量相关问题 | 花猪のBlog</title><meta name="keywords" content="操作系统"><meta name="author" content="花猪,2296412185@qq.com"><meta name="copyright" content="花猪"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="记录操作系统学习历程">
<meta property="og:type" content="article">
<meta property="og:title" content="操作系统学习笔记-信号量相关问题">
<meta property="og:url" content="https://cnhuazhu.top/2021/04/25/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98/index.html">
<meta property="og:site_name" content="花猪のBlog">
<meta property="og:description" content="记录操作系统学习历程">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/OperatingSystemscover1.png">
<meta property="article:published_time" content="2021-04-25T09:30:29.000Z">
<meta property="article:modified_time" content="2021-06-30T12:31:09.556Z">
<meta property="article:author" content="花猪">
<meta property="article:tag" content="操作系统">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/OperatingSystemscover1.png"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/avatar.jpg"><link rel="canonical" href="https://cnhuazhu.top/2021/04/25/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":60,"languages":{"author":"作者: 花猪","link":"链接: ","source":"来源: 花猪のBlog","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#ABADAC","bgDark":"#121212","position":"bottom-right"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '操作系统学习笔记-信号量相关问题',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-06-30 20:31:09'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="/css/tag.css"><link rel="stylesheet" href="/css/pagelucency.css"><style>#article-container.post-content h1:before, h2:before, h3:before, h4:before, h5:before, h6:before { -webkit-animation: avatar_turn_around 1s linear infinite; -moz-animation: avatar_turn_around 1s linear infinite; -o-animation: avatar_turn_around 1s linear infinite; -ms-animation: avatar_turn_around 1s linear infinite; animation: avatar_turn_around 1s linear infinite; }</style><link rel="stylesheet" href="/css/avatarbg.css"><link rel="stylesheet" href="/css/footerlucency.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/macblack.css"><link rel="stylesheet" href="/css/mouse.css"><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-butterfly-swiper/lib/swiper.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-butterfly-swiper/lib/swiperstyle.css"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.3.0"><link rel="alternate" href="/atom.xml" title="花猪のBlog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="wizard-scene"><div class="wizard-objects"><div class="wizard-square"></div><div class="wizard-circle"></div><div class="wizard-triangle"></div></div><div class="wizard"><div class="wizard-body"></div><div class="wizard-right-arm"><div class="wizard-right-hand"></div></div><div class="wizard-left-arm"><div class="wizard-left-hand"></div></div><div class="wizard-head"><div class="wizard-beard"></div><div class="wizard-face"><div class="wizard-adds"></div></div><div class="wizard-hat"><div class="wizard-hat-of-the-hat"></div><div class="wizard-four-point-star --first"></div><div class="wizard-four-point-star --second"></div><div class="wizard-four-point-star --third"></div></div></div></div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">86</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">20</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="http://cnhuazhu.top/"><i class="fa-fw fas fa-gift"></i><span> 引导</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-sitemap"></i><span> 分站</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="http://cnhuazhu.top/next"><i class="fa-fw fas fa-chevron-right"></i><span> Next</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 生活</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 图库</span></a></li><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 阅读</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/video/"><i class="fa-fw fa fa-video"></i><span> 视频</span></a></li><li><a class="site-page child" href="/artitalk/"><i class="fa-fw fas fa-quote-left"></i><span> 说说</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 链接</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></li><li><a class="site-page child" href="/website/"><i class="fa-fw fas fa-globe"></i><span> 网站</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/Message/"><i class="fa-fw fas fa-comment"></i><span> 留言</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div></div></div><div id="body-wrap"><header class="post-bg" id="page-header" style="background: transparent"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">花猪のBlog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="http://cnhuazhu.top/"><i class="fa-fw fas fa-gift"></i><span> 引导</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-sitemap"></i><span> 分站</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="http://cnhuazhu.top/next"><i class="fa-fw fas fa-chevron-right"></i><span> Next</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 生活</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 图库</span></a></li><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 阅读</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/video/"><i class="fa-fw fa fa-video"></i><span> 视频</span></a></li><li><a class="site-page child" href="/artitalk/"><i class="fa-fw fas fa-quote-left"></i><span> 说说</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 链接</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></li><li><a class="site-page child" href="/website/"><i class="fa-fw fas fa-globe"></i><span> 网站</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/Message/"><i class="fa-fw fas fa-comment"></i><span> 留言</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">操作系统学习笔记-信号量相关问题</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-04-25T09:30:29.000Z" title="发表于 2021-04-25 17:30:29">2021-04-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-06-30T12:31:09.556Z" title="更新于 2021-06-30 20:31:09">2021-06-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">5.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>18分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="操作系统学习笔记-信号量相关问题"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1>前言</h1>
<p><em>正在学习操作系统，记录笔记。</em></p>
<p>（补充一下与信号量相关的问题类型以及解决思路）</p>
<blockquote>
<p>参考资料：</p>
<p>《操作系统（精髓与设计原理 第6版） 》</p>
<p>王道考研：<a target="_blank" rel="noopener external nofollow noreferrer" href="https://www.bilibili.com/video/BV1YE411D7nH?from=search&amp;seid=12220712596266554764">2019 王道考研 操作系统_哔哩哔哩 (゜-゜)つロ 干杯~-bilibili</a></p>
</blockquote>
<hr>
<h1>正文</h1>
<p>先声明：为了方便（就是我懒），下文可能会用<code>P操作</code>来指代<code>semWait(x)</code>；用<code>V操作</code>来指代<code>semSignal(x)</code>。</p>
<h2 id="生产者-消费者问题">生产者-消费者问题</h2>
<p>问题描述：</p>
<ul>
<li>
<p>系统中有一组生产者进程和一组消费者进程，生产者进程每次生产一个产品放入缓冲区，消费者进程每次从缓冲区中取出一个产品并使用。（注：这里的“产品理解为某种数据”）</p>
</li>
<li>
<p>生产者、消费者共享一个初始为空、大小为n的缓冲区。</p>
</li>
<li>
<p>只有缓冲区没满时，生产者才能把产品放入缓冲区，否则必须等待。</p>
</li>
<li>
<p>只有缓冲区不空时，消费者才能从中取出产品，否则必须等待。</p>
</li>
<li>
<p>缓冲区是临界资源，各进程必须互斥地访问（只允许一个生产者放入消息，也只允许一个消费者拿出消息）。</p>
<blockquote>
<p>再次详细解释一下最后一点。意思是，同一个时刻只能是一个生产者或者一个消费者操作缓冲区，禁止以下情况：多个生产者或者多个消费者操作缓冲区；同样，一个生产者和一个消费者同时操作也是禁止的。</p>
</blockquote>
</li>
</ul>
<p>分析：</p>
<ul>
<li>互斥关系：不允许有两方及以上同时访问缓冲区。</li>
<li>同步关系：存在两种同步关系，分别为缓冲区满、缓冲区空。（当消费者消费一个产品，应该告诉生产者，缓冲区有一个空位；当生产者生产一个商品，应该告诉消费者，缓冲区非空）</li>
</ul>
<p>所以根据以上分析得知：应该需要三对P、V操作。因此需要定义如下三个信号量：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">semaphore mutex = <span class="number">1</span>;    <span class="comment">//互斥信号量，实现对缓冲区的访问</span></span><br><span class="line">semaphore empty = n;    <span class="comment">//同步信号量，表示空闲缓冲区的数量（初始值为n）</span></span><br><span class="line">semaphore full = <span class="number">0</span>;    <span class="comment">//同步信号量，表示产品的数量，也即非缓冲区的数量（初始值为0）</span></span><br></pre></td></tr></table></figure>
<p>实现：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*producer*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">producer</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        <span class="comment">/*生产一个产品*/</span>;</span><br><span class="line">        semWait(empty);    <span class="comment">//检查有无缓冲区可用  (Ⅰ)</span></span><br><span class="line">        semWait(mutex);    <span class="comment">//互斥操作  (Ⅱ)</span></span><br><span class="line">        <span class="comment">/*将产品放入缓冲区*/</span>;</span><br><span class="line">        semSignal(mutex);    <span class="comment">//互斥操作</span></span><br><span class="line">        semSignal(full);    <span class="comment">//告诉消费者“生产了一个产品”</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*consumer*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">consumer</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        semWait(full);    <span class="comment">//检查有无产品（非空缓冲区）  (Ⅲ)</span></span><br><span class="line">        semWait(mutex);    <span class="comment">//互斥操作  (Ⅳ)</span></span><br><span class="line">        <span class="comment">/*从缓冲区中取出一个产品*/</span>;</span><br><span class="line">        semSignal(mutex);    <span class="comment">//互斥操作</span></span><br><span class="line">        semSignal(empty);    <span class="comment">//告诉生产者“取走了一个产品，缓冲区有空闲”</span></span><br><span class="line">        <span class="comment">/*使用产品*/</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    parbegin(producer(), consumer());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>思考：能否改变相邻P、V操作的顺序？（即调换<code>(Ⅰ)</code>、<code>(Ⅱ)</code>以及<code>(Ⅲ)</code>、<code>(Ⅳ)</code>的顺序）</p>
<p>分析：</p>
<ul>
<li>分析此种情况：若缓冲区内已经放满产品，则empty=0，full=n。</li>
<li>则生产者先执行<code>(Ⅱ)</code>（semWait(mutex)）操作使得mutex变为0，在执行<code>(Ⅰ)</code>操作（semWait(empty)），由于已经没有空闲缓冲区，因此生产者被阻塞。接着切换至消费者进程。消费者进程首先执行<code>(Ⅳ)</code>（semWait(mutex)）操作，由于mutex为0，即生产者还没有释放对临界资源的控制权，因此消费者也被阻塞。</li>
<li>这就出现了<strong>死锁</strong>的情况（生产者等待消费者释放空闲缓冲区，而消费者又等待生产者释放临界区）</li>
<li>同样的我们分析另一种情况：若缓冲区中没有产品，即empty=n，full=0。按照<code>(Ⅳ)``(Ⅲ)``(Ⅱ)</code>的顺序也会发生死锁情况。</li>
</ul>
<p>因此：</p>
<ul>
<li><strong>实现互斥的P操作一定要在实现同步的P操作之后。</strong></li>
<li><strong>V操作不会导致进程阻塞，因此两个V操作顺序可以交换。</strong></li>
</ul>
<p>还需要注意的一点：</p>
<p>生产者<code>“生产一个产品”</code>的操作以及消费者<code>“使用产品”</code>的操作可以放置P、V操作之间，但是要意识到这些操作是非必要的，如果放置在临界区操作则会导致其代码量变大，在一个进程访问临界区的同时就要耗费更多的时间，这会导致进程之间的并发度降低。（<strong>只在临界区做必要操作</strong>）</p>
</blockquote>
<h2 id="多生产者-多消费者问题">多生产者-多消费者问题</h2>
<p>问题描述：</p>
<p>桌子上有一只盘子，每次只能向其中放入一个水果。爸爸专向盘子中放苹果，妈妈专向盘子中放橘子，儿子专等着吃盘子中的橘子，女儿专等着吃盘子中的苹果。只有盘子空时，爸爸或妈妈才可向盘子中放一个水果。仅当盘子中有自己需要的水果时，儿子或女儿可以从盘子中取出水果。用P、V操作实现上述过程。</p>
<p>分析：</p>
<ul>
<li>互斥关系：将盘子视为缓冲区。每个人（进程）对其访问都是互斥的。</li>
<li>同步关系：
<ol>
<li>父亲将苹果放入盘子后，女儿才能取苹果。</li>
<li>母亲将橘子放入盘子后，儿子才能取橘子。</li>
<li>只有盘子为空时，父亲或母亲才能放入水果。（盘子为空事件可由儿子或者女儿触发）</li>
</ol>
</li>
</ul>
<p>所以根据以上分析得知，需要定义如下四个信号量：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">semaphore mutex = <span class="number">1</span>;    <span class="comment">//实现互斥访问盘子（临界区）</span></span><br><span class="line">semaphore apple = <span class="number">0</span>;    <span class="comment">//盘子中有几个苹果（初始值为0）</span></span><br><span class="line">semaphore orange = <span class="number">0</span>;    <span class="comment">//盘子中有几个橘子（初始值为0）</span></span><br><span class="line">semaphore plate = <span class="number">1</span>;    <span class="comment">//盘子中还可以放多少个水果</span></span><br></pre></td></tr></table></figure>
<p>实现：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*dad*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">dad</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        <span class="comment">/*准备一个苹果*/</span>;</span><br><span class="line">        semWait(plate);    <span class="comment">//检查盘子是否为空</span></span><br><span class="line">        semWait(mutex);    <span class="comment">//实现对盘子这一缓冲区的互斥访问</span></span><br><span class="line">        <span class="comment">/*把苹果放入盘子*/</span>;</span><br><span class="line">        semSignal(mutex);</span><br><span class="line">        semSignal(apple);    <span class="comment">//告诉女儿“盘子里有苹果了”</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*mom*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">mom</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        <span class="comment">/*准备一个橘子*/</span>;</span><br><span class="line">        semWait(plate);    <span class="comment">//检查盘子是否为空</span></span><br><span class="line">        semWait(mutex);    <span class="comment">//实现对盘子这一缓冲区的互斥访问</span></span><br><span class="line">        <span class="comment">/*把橘子放入盘子*/</span>;</span><br><span class="line">        semSignal(mutex);</span><br><span class="line">        semSignal(orange);    <span class="comment">//告诉儿子“盘子里有橘子了”</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*daughter*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">daughter</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        semWait(apple);    <span class="comment">//检查盘子里有没有苹果</span></span><br><span class="line">        semWait(mutex);    <span class="comment">//实现对盘子这一缓冲区的互斥访问</span></span><br><span class="line">        <span class="comment">/*从盘子中取出苹果*/</span>;</span><br><span class="line">        semSignal(mutex);</span><br><span class="line">        semSignal(plate);    <span class="comment">//告诉父母“盘子为空了”</span></span><br><span class="line">        <span class="comment">/*吃掉苹果*/</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*son*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">son</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        semWait(orange);    <span class="comment">//检查盘子里有没有橘子</span></span><br><span class="line">        semWait(mutex);    <span class="comment">//实现对盘子这一缓冲区的互斥访问</span></span><br><span class="line">        <span class="comment">/*从盘子中取出橘子*/</span>;</span><br><span class="line">        semSignal(mutex);</span><br><span class="line">        semSignal(plate);    <span class="comment">//告诉父母“盘子为空了”</span></span><br><span class="line">        <span class="comment">/*吃掉橘子*/</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    parbegin(dad(), mom(), daughter(), son());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>思考：上述案例可不可以不使用互斥信号量（mutex）呢？</p>
<p>分析（删除上述代码中所有的<code>semWait(mutex)</code>以及<code>semSignal(mutex)</code>操作）：</p>
<ul>
<li>刚开始，儿子、女儿进程即使上处理机运行也会被阻塞。</li>
<li>如果刚开始是父亲进程先上处理机运行，则：
<ul>
<li>父亲执行<code>semWait(plate)</code>操作，可以访问盘子。</li>
<li>母亲执行<code>semWait(plate)</code>操作，被阻塞等待盘子。</li>
<li>父亲执行<code>semSignal(apple)</code>操作，放入苹果。</li>
<li>女儿i进程被唤醒（其他进程即使运行也会阻塞）。</li>
<li>女儿执行<code>semWait(apple)</code>操作，访问盘子。并接着执行<code>semSignal(plate)</code>操作。</li>
<li>父亲或者母亲进程再次被唤醒（儿子进程访问会被阻塞）。</li>
<li>…</li>
</ul>
</li>
</ul>
<p>以上分析可以得出结论，即便没有互斥信号量（mutex），也不影响正常运行。</p>
<p>原因在于：本题中的缓冲区大小为1，在任何时刻，apple、orange、plate三个同步信号量中最多只有一个是1。因此在任何时刻，最多只有一个进程的<code>P操作</code>不会被阻塞，并顺利地进入临界区。</p>
<p>但是加入此题盘子的容量为2及以上，就无法保证进程互斥访问盘子。（分析过程省略）</p>
<p><strong>最好直接就设置互斥信号量（mutex），以防出错。</strong></p>
</blockquote>
<h2 id="吸烟者问题">吸烟者问题</h2>
<p>问题描述：</p>
<p>假设一个系统有三个抽烟者进程和一个供应者进程。每个抽烟者不停地卷烟并抽掉它，但是要卷起并抽掉一支烟，抽烟者需要有三种材料：烟草、纸和胶水。三个抽烟者中，第一个拥有烟草、第二个拥有纸、第三个拥有胶水。供应者进程无限地提供三种材料，供应者每次将两种材料放桌子上，拥有剩下第三种材料的抽烟者卷一根烟并抽掉它，并给供应者进程一个信号告诉完成了，供应者就会放另外两种材料再桌上，这个过程一直重复（让三个抽烟者轮流地抽烟）</p>
<p>分析：</p>
<ul>
<li>
<p>互斥关系：将桌子视为缓冲区，每个进程对其访问都是互斥的。</p>
<blockquote>
<p>值得注意的是，尽管供应者每次会将两种材料放置在桌子上，但是桌子（缓冲区）的容量仍为1，我们应该将不同的两种材料视为一种组合：</p>
<ul>
<li>组合一：纸 + 胶水</li>
<li>组合二：烟草 + 胶水</li>
<li>组合三：烟草 + 纸</li>
</ul>
</blockquote>
</li>
<li>
<p>同步关系：</p>
<ol>
<li>桌上有组合一 → 第一个抽烟者取走东西。</li>
<li>桌上有组合二 → 第二个抽烟者取走东西。</li>
<li>桌上有组合三 → 第三个抽烟者取走东西。</li>
<li>抽烟者抽完烟 → 供应者将下一种组合材料放到桌子上。</li>
</ol>
</li>
<li>
<p>需要让三个抽烟者轮流地抽烟。</p>
</li>
</ul>
<p>所以根据以上分析得知，需要定义如下四个信号量：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">semaphore offer1 = <span class="number">0</span>;    <span class="comment">//桌上组合一的数量</span></span><br><span class="line">semaphore offer2 = <span class="number">0</span>;    <span class="comment">//桌上组合二的数量</span></span><br><span class="line">semaphore offer3 = <span class="number">0</span>;    <span class="comment">//桌上组合三的数量</span></span><br><span class="line">semaphore finish = <span class="number">0</span>;    <span class="comment">//抽烟是否完成</span></span><br><span class="line"><span class="keyword">int</span> i = <span class="number">0</span>;    <span class="comment">//用于实现“三个抽烟者轮流地抽烟”</span></span><br></pre></td></tr></table></figure>
<p>实现：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*provider*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">provider</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        <span class="keyword">if</span>(i == <span class="number">0</span>)&#123;</span><br><span class="line">            <span class="comment">/*将组合一放桌上*/</span>;</span><br><span class="line">            semSignal(offer1);    <span class="comment">//告诉第一个抽烟者“桌上有组合一”</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span>(i == <span class="number">1</span>)&#123;</span><br><span class="line">            <span class="comment">/*将组合二放桌上*/</span>;</span><br><span class="line">            semSignal(offer2);    <span class="comment">//告诉第二个抽烟者“桌上有组合二”</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span>(i == <span class="number">2</span>)&#123;</span><br><span class="line">            <span class="comment">/*将组合三放桌上*/</span>;</span><br><span class="line">            semSignal(offer3);    <span class="comment">//告诉第三个抽烟者“桌上有组合三”</span></span><br><span class="line">        &#125;</span><br><span class="line">        i = (i + <span class="number">1</span>) % <span class="number">3</span>;</span><br><span class="line">        semWait(finish);    <span class="comment">//判断抽烟者是否已经完成吸烟</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*smoker1*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">smoker1</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        semWait(offer1);    <span class="comment">//判断桌子上有没有组合一</span></span><br><span class="line">        <span class="comment">/*从桌子上拿走组合一；卷烟；抽掉*/</span>;</span><br><span class="line">        semSignal(finish);    <span class="comment">//告诉提供者“桌子上已经空了”</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*smoker2*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">smoker2</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        semWait(offer2);    <span class="comment">//判断桌子上有没有组合二</span></span><br><span class="line">        <span class="comment">/*从桌子上拿走组合二；卷烟；抽掉*/</span>;</span><br><span class="line">        semSignal(finish);    <span class="comment">//告诉提供者“桌子上已经空了”</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*smoker3*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">smoker3</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        semWait(offer3);    <span class="comment">//判断桌子上有没有组合三</span></span><br><span class="line">        <span class="comment">/*从桌子上拿走组合三；卷烟；抽掉*/</span>;</span><br><span class="line">        semSignal(finish);    <span class="comment">//告诉提供者“桌子上已经空了”</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    parbegin(provider(), smoker1(), smoker2(), smoker3());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>分析：是否需要专门再设置一个互斥信号量（mutex）？</p>
<p>因为桌子的容量为1（同上面一个例子相同），因此不必设置也不会出错。</p>
</blockquote>
<h2 id="读者-写者问题">读者-写者问题</h2>
<p>问题描述：</p>
<p>有读者和写者两组并发进程，共享一个文件，当两个或两个以上的读进程同时访问共享数据时不会产生副作用，但若某个写进程和其他进程（读进程或写进程）同时访问共享数据时则可能导致数据不一致的错误。因此我们要求：</p>
<ul>
<li>允许多个读者可以同时对文件执行读操作；</li>
<li>只允许一个写者往文件中写信息；</li>
<li>任一写者在完成写操作之前不允许其他读者或写者工作；</li>
<li>写者执行写操作前，应让已有的读者和写者全部退出。</li>
</ul>
<p>分析：</p>
<ul>
<li>
<p>互斥关系：</p>
<ol>
<li>
<p>写进程——写进程</p>
</li>
<li>
<p>写进程——读进程</p>
<p>（读进程之间不存在互斥关系，因此可以同时读文件，如何实现该操作是此类问题的关键）</p>
</li>
</ol>
</li>
</ul>
<p>所以根据以上分析得知，需要定义如下三个信号量：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">semaphore rw = <span class="number">1</span>;    <span class="comment">//用于实现对文件的互斥访问。表示当前是否有进程在访问共享文件</span></span><br><span class="line"><span class="keyword">int</span> count = <span class="number">0</span>;    <span class="comment">//用于记录当前有几个读进程在访问文件</span></span><br><span class="line">semaphore mutex = <span class="number">1</span>;    <span class="comment">//用于保证对count变量的互斥访问</span></span><br></pre></td></tr></table></figure>
<p>实现：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*writer*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">writer</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        semWait(rw);    <span class="comment">//在写文件之前“上锁”</span></span><br><span class="line">        <span class="comment">/*写文件*/</span>;</span><br><span class="line">        semSignal(rw);    <span class="comment">//在写完之后“解锁”</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*reader*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">reader</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        semWait(mutex);    <span class="comment">//各读进程互斥访问count</span></span><br><span class="line">        <span class="keyword">if</span>(count == <span class="number">0</span>)&#123;</span><br><span class="line">            semWait(rw);    <span class="comment">//第一个读进程负责“上锁”</span></span><br><span class="line">        &#125;</span><br><span class="line">        count++;    <span class="comment">//访问文件的读进程数加一</span></span><br><span class="line">        semSignal(mutex);    </span><br><span class="line">        <span class="comment">/*读文件*/</span>;</span><br><span class="line">        semWait(mutex);    <span class="comment">//各读进程互斥访问count</span></span><br><span class="line">        count--;    <span class="comment">//访问文件的读进程数减一</span></span><br><span class="line">        <span class="keyword">if</span>(count == <span class="number">0</span>)&#123;</span><br><span class="line">            semSignal(rw);    <span class="comment">//最后一个读进程负责“解锁”</span></span><br><span class="line">        &#125;</span><br><span class="line">        semSignal(mutex);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    parbegin(writer(), reader1(), reader2(),...,readern());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>分析：</p>
<p>mutex变量的设置是为了解决读进程对count的访问（解决多个读进程访问的操作）</p>
<ul>
<li>第一个读进程执行<code>semWait(mutex)</code>操作，顺利通过，并执行之后的<code>semWait(rw)</code>操作（保证了读进程与写进程的互斥）</li>
<li>若此时另一个读进程访问，在执行<code>semWait(mutex)</code>操作会被阻塞，直到第一个读进程执行<code>semSignal(mutex)</code>操作（“解锁”对count的访问，注意此时count值为1）</li>
<li>当count“解锁”后，另一个读进程再执行<code>semWait(mutex)</code>操作，判断count的值不为0，直接跳过<code>semWait(rw)</code>访问，这样就避免了各个读进程之间的互斥访问</li>
</ul>
<p>再仔细体会会发现上述代码存在一个潜在的问题，即：如果读进程一直在不停地访问（count值永不为0），就无法对文件“解锁”，写者进程就可能“饿死”。</p>
<p>因此该种写法是<strong>读进程优先</strong>。</p>
</blockquote>
<p>如何实现写进程优先呢？</p>
<p>这里我们再增加一个信号量：<code>semaphore w = 1</code>。</p>
<p>即现在一共有如下四个信号量：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">semaphore rw = <span class="number">1</span>;    <span class="comment">//用于实现对文件的互斥访问。表示当前是否有进程在访问共享文件</span></span><br><span class="line"><span class="keyword">int</span> count = <span class="number">0</span>;    <span class="comment">//用于记录当前有几个读进程在访问文件</span></span><br><span class="line">semaphore mutex = <span class="number">1</span>;    <span class="comment">//用于保证对count变量的互斥访问</span></span><br><span class="line">semaphore w = <span class="number">1</span>;    <span class="comment">//用于实现“写进程优先”</span></span><br></pre></td></tr></table></figure>
<p>实现：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*writer*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">writer</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        semWait(w);    <span class="comment">//Ⅰ</span></span><br><span class="line">        semWait(rw);    <span class="comment">//在写文件之前“上锁”  Ⅱ</span></span><br><span class="line">        <span class="comment">/*写文件*/</span>;</span><br><span class="line">        semSignal(rw);    <span class="comment">//在写完之后“解锁”  Ⅲ</span></span><br><span class="line">        semSignal(w);    <span class="comment">//Ⅳ</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*reader*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">reader</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        semWait(w);    <span class="comment">//Ⅴ</span></span><br><span class="line">        semWait(mutex);    <span class="comment">//各读进程互斥访问count  </span></span><br><span class="line">        <span class="keyword">if</span>(count == <span class="number">0</span>)&#123;</span><br><span class="line">            semWait(rw);    <span class="comment">//第一个读进程负责“上锁”  Ⅵ</span></span><br><span class="line">        &#125;</span><br><span class="line">        count++;    <span class="comment">//访问文件的读进程数加一</span></span><br><span class="line">        semSignal(mutex);</span><br><span class="line">        semSignal(w);    <span class="comment">//Ⅶ</span></span><br><span class="line">        <span class="comment">/*读文件*/</span>;</span><br><span class="line">        semWait(mutex);    <span class="comment">//各读进程互斥访问count</span></span><br><span class="line">        count--;    <span class="comment">//访问文件的读进程数减一</span></span><br><span class="line">        <span class="keyword">if</span>(count == <span class="number">0</span>)&#123;</span><br><span class="line">            semSignal(rw);    <span class="comment">//最后一个读进程负责“解锁”  Ⅷ</span></span><br><span class="line">        &#125;</span><br><span class="line">        semSignal(mutex);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    parbegin(writer(), reader1(), reader2(),...,readern());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>分析：<em>（容我吐槽一下，简直头皮发麻）</em></p>
<ol>
<li>
<p>读者1 → 读者2</p>
<ul>
<li>第一个读进程顺利通过<code>Ⅴ（semWait(w)）</code>操作，并对文件（rw）“上锁”，count++，…，到最后顺利地读文件。</li>
<li>第二个读进程同上。</li>
<li>即在增添了<code>Ⅴ（semWait(w)）</code>操作以及<code>Ⅶ（semSignal(w)）</code>对多个读进程并发访问文件是没有影响的。</li>
</ul>
</li>
<li>
<p>写者1 → 写者2</p>
<ul>
<li>第一个写进程会顺利通过<code>Ⅰ（semWait(w)）</code>操作，<code>Ⅱ（semWait(rw)）</code>操作，并顺利写文件。</li>
<li>第二个写进程如果并发执行会被阻塞在Ⅰ处，直到第一个写进程执行<code>Ⅳ（semSignal(w)）</code>“解锁写操作”，才可以继续执行。</li>
<li>实现了多个写进程之间的互斥。</li>
</ul>
</li>
<li>
<p>写者1 → 读者1</p>
<ul>
<li>写着进程顺利通过<code>Ⅰ（semWait(w)）</code>操作，<code>Ⅱ（semWait(rw)）</code>操作，开始写文件。</li>
<li>此时如果读进程要执行，就会被阻塞在<code>Ⅴ（semWait(w)）</code>操作，直到写进程执行完<code>Ⅳ（semSignal(w)）</code>“解锁写操作”，才可以继续执行。</li>
<li>实现了读者与写者的互斥。</li>
</ul>
</li>
<li>
<p>读者1 → 写者1 → 读者2</p>
<ul>
<li>第一个读进程可以顺利执行到<code>读文件</code>操作。</li>
<li>此时若写进程执行，可以顺利执行<code>Ⅰ（semWait(w)）</code>操作，但在<code>Ⅱ（semWait(rw)）</code>操作会被阻塞。</li>
<li>然后第二个读进程并发执行，由于上一步读进程顺利执行<code>Ⅰ（semWait(w)）</code>操作，所以第二个读进程会被阻塞在<code>Ⅴ（semWait(w)）</code>操作。</li>
<li>直到第一个读进程执行完<code>Ⅷ（semSignal(rw)）</code>操作对文件“解锁”，此时写进程就可以被唤醒，开始写文件。</li>
<li>第二个读进程依然被阻塞在<code>Ⅴ（semWait(w)）</code>操作，直到写进程执行完<code>Ⅳ（semSignal(w)）</code>操作，第二个读进程才可以继续执行。</li>
<li>所以这种情况并不会导致写进程“饥饿”。</li>
</ul>
</li>
<li>
<p>写者1 → 读者1 → 写者2</p>
<ul>
<li>
<p>第一个写进程顺利执行前面的操作，开始写文件。</p>
</li>
<li>
<p>此时如果读进程执行，则会被阻塞在<code>Ⅴ（semWait(w)）</code>操作。</p>
</li>
<li>
<p>此时如果第二个写进程执行，则也会被阻塞在<code>Ⅰ（semWait(w)）</code>操作。</p>
</li>
<li>
<p>如果第一个写进程执行完<code>Ⅳ（semSignal(w)）</code>操作，则此时会根据“先来先得”的原则，首先唤醒读进程，读进程顺利执行。</p>
</li>
<li>
<p>然后读进程会执行<code>Ⅵ（semWait(rw)）</code>操作对文件“上锁”，在执行完<code>Ⅶ（semWait(w)）</code>操作时释放对写进程的操作，第二个写进程就继续执行，但是会被阻塞在<code>Ⅱ（semWait(rw)）</code>操作。</p>
</li>
<li>
<p>读进程继续执行，直到结束，释放对文件的访问控制，第二个写进程才可以顺利执行。</p>
</li>
<li>
<blockquote>
<p>在这种情况我们可以分析出，尽管不会使得写进程“饥饿”，但也不是真正的“写进程优先”，而是符合相对公平的先来先服务的原则。</p>
</blockquote>
</li>
</ul>
</li>
</ol>
</blockquote>
<h2 id="哲学家进餐问题">哲学家进餐问题</h2>
<p>问题描述：</p>
<p>一张圆桌上坐着5名哲学家，每两个哲学家之间的桌上摆一根筷子，桌子的中间是一碗米饭。哲学家们倾注毕生的精力用于思考和进餐，哲学家在思考时，并不影响他人。只有当哲学家饥饿时，才试图拿起左、右两根筷子（一根一根地拿起）。如果筷子已在他人手上，则需等待。饥饿的哲学家只有同时拿起两根筷子才可以开始进餐，当进餐完毕后，放下筷子继续思考。</p>
<p><img src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/OS%E5%93%B2%E5%AD%A6%E5%AE%B6%E8%BF%9B%E9%A4%90%E9%97%AE%E9%A2%98.png" alt=""></p>
<p>分析：</p>
<ul>
<li>
<p>互斥关系：系统中有5个哲学家进程，5位哲学家与左右邻居对其中间筷子的访问是互斥关系。</p>
<blockquote>
<p>这个问题中只有互斥关系，但与之前遇到的问题不同的是，每个哲学家进程需要同时持有两个临界资源才能开始吃饭。如何避免临界资源分配不当造成的死锁现象，是哲学家问题的关键。</p>
</blockquote>
</li>
</ul>
<p>所以根据以上分析得知，需要定义如下信号量数组以及一个互斥信号量：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">semaphore chopstick[<span class="number">5</span>] = &#123;<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>&#125;;    <span class="comment">//用于实现对5根筷子的互斥访问</span></span><br><span class="line">semaphore mutex = <span class="number">1</span>;    <span class="comment">//互斥地取筷子</span></span><br></pre></td></tr></table></figure>
<p>并规定对哲学家按0~4编号，哲学家 i 左边的筷子编号为 i，右边的筷子编号为 <code>( i + 1 ) % 5</code>。</p>
<p>实现：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*philosopher*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">philosopher</span><span class="params">(<span class="keyword">int</span> i)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        <span class="comment">/*思考*/</span>;</span><br><span class="line">        semWait(mutex);</span><br><span class="line">        semWait(chopstick[i]);    <span class="comment">//拿起左筷</span></span><br><span class="line">        semWait(chopstick[(i+<span class="number">1</span>)%<span class="number">5</span>]);    <span class="comment">//拿起右筷</span></span><br><span class="line">        semSignal(mutex);</span><br><span class="line">        <span class="comment">/*进餐*/</span>;</span><br><span class="line">        semSignal(chopstick[i]);    <span class="comment">//放下左筷</span></span><br><span class="line">        semSignal(shopstick[(i+<span class="number">1</span>)%<span class="number">5</span>]);    <span class="comment">//放下右筷</span></span><br><span class="line">        <span class="comment">/*思考*/</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    parbegin (philosopher(<span class="number">0</span>), philosopher(<span class="number">1</span>), philosopher(<span class="number">2</span>), philosopher(<span class="number">3</span>), philosopher(<span class="number">4</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>分析：</p>
<p>哲学家进程要想正常进行就需要同时拿起左右两根筷子，一旦请求资源无法满足，就会进入阻塞态。</p>
</blockquote>
<p>方法二：</p>
<p>分析：根据“鸽笼原理”，只要最多只有四位哲学家并发争夺筷子进餐，那么肯定会有一位哲学家可以同时拿到两根筷子。为此我们定义如下信号量：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">semaphore chopstick[<span class="number">5</span>] = &#123;<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>&#125;;    <span class="comment">//用于实现对5根筷子的互斥访问</span></span><br><span class="line">semaphore room = <span class="number">4</span>;    <span class="comment">//最多允许4为哲学家进餐</span></span><br></pre></td></tr></table></figure>
<p>实现：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*philosopher*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">philosopher</span><span class="params">(<span class="keyword">int</span> i)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        <span class="comment">/*思考*/</span>;</span><br><span class="line">        semWait(room);</span><br><span class="line">        semWait(chopstick[i]);    <span class="comment">//拿起左筷</span></span><br><span class="line">        semWait(chopstick[(i+<span class="number">1</span>)%<span class="number">5</span>]);    <span class="comment">//拿起右筷</span></span><br><span class="line">        <span class="comment">/*进餐*/</span>;</span><br><span class="line">        semSignal(chopstick[i]);    <span class="comment">//放下左筷</span></span><br><span class="line">        semSignal(shopstick[(i+<span class="number">1</span>)%<span class="number">5</span>]);    <span class="comment">//放下右筷</span></span><br><span class="line">        semSignal(room);</span><br><span class="line">        <span class="comment">/*思考*/</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    parbegin (philosopher(<span class="number">0</span>), philosopher(<span class="number">1</span>), philosopher(<span class="number">2</span>), philosopher(<span class="number">3</span>), philosopher(<span class="number">4</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>方法三：</p>
<p>要求奇数号哲学家先拿左边的筷子，然后再拿右边的筷子；而偶数号的哲学家相反，先拿右边的筷子，再拿左边的筷子。在这种策略下，如果相邻的两个奇偶号哲学家都想吃饭，那么只会有其中一个可以拿起第一只筷子，另一个会直接阻塞。这就避免了占有一支后再等待另一支的情况。</p>
<p>首先定义如下信号量：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">semaphore chopstick[<span class="number">5</span>] = &#123;<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>,<span class="number">1</span>&#125;;    <span class="comment">//用于实现对5根筷子的互斥访问</span></span><br></pre></td></tr></table></figure>
<p>实现：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*philosopher*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">philosopher</span><span class="params">(<span class="keyword">int</span> i)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">while</span>(<span class="number">1</span>)&#123;</span><br><span class="line">        <span class="keyword">if</span>(i % <span class="number">2</span> == <span class="number">1</span>)&#123;    <span class="comment">//奇数号哲学家</span></span><br><span class="line">            <span class="comment">/*思考*/</span>;</span><br><span class="line">            semWait(chopstick[i]);    <span class="comment">//拿起左筷</span></span><br><span class="line">            semWait(chopstick[(i+<span class="number">1</span>)%<span class="number">5</span>]);    <span class="comment">//拿起右筷</span></span><br><span class="line">            <span class="comment">/*进餐*/</span>;</span><br><span class="line">            semSignal(chopstick[i]);    <span class="comment">//放下左筷</span></span><br><span class="line">            semSignal(shopstick[(i+<span class="number">1</span>)%<span class="number">5</span>]);    <span class="comment">//放下右筷</span></span><br><span class="line">            <span class="comment">/*思考*/</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(i % <span class="number">2</span> == <span class="number">0</span>)&#123;    <span class="comment">//偶数号哲学家</span></span><br><span class="line">            <span class="comment">/*思考*/</span>;</span><br><span class="line">            semWait(chopstick[(i+<span class="number">1</span>)%<span class="number">5</span>]);    <span class="comment">//拿起右筷</span></span><br><span class="line">            semWait(chopstick[i]);    <span class="comment">//拿起左筷</span></span><br><span class="line">            <span class="comment">/*进餐*/</span>;</span><br><span class="line">            semSignal(shopstick[(i+<span class="number">1</span>)%<span class="number">5</span>]);    <span class="comment">//放下右筷</span></span><br><span class="line">            semSignal(chopstick[i]);    <span class="comment">//放下左筷</span></span><br><span class="line">            <span class="comment">/*思考*/</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    parbegin (philosopher(<span class="number">0</span>), philosopher(<span class="number">1</span>), philosopher(<span class="number">2</span>), philosopher(<span class="number">3</span>), philosopher(<span class="number">4</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h1>后记</h1>
<p>本篇还没结束，持续更新中。</p>
<p><em>（欢迎评论区批评指正）</em></p>
</article><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">操作系统</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/OperatingSystemscover1.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/wechat.png" rel="external nofollow noreferrer" target="_blank"><img class="post-qr-code-img" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/alipay.jpg" rel="external nofollow noreferrer" target="_blank"><img class="post-qr-code-img" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2021/03/14/操作系统/操作系统学习笔记-计算机系统概述/" title="操作系统学习笔记-计算机系统概述"><img class="cover" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/OperatingSystemscover1.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-14</div><div class="title">操作系统学习笔记-计算机系统概述</div></div></a></div><div><a href="/2021/03/28/操作系统/操作系统学习笔记/" title="操作系统学习笔记"><img class="cover" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/RotatingImage7.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-28</div><div class="title">操作系统学习笔记</div></div></a></div><div><a href="/2021/06/02/操作系统/操作系统学习笔记-I-O管理和磁盘调度/" title="操作系统学习笔记-I/O管理和磁盘调度"><img class="cover" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/OperatingSystemscover1.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-06-02</div><div class="title">操作系统学习笔记-I/O管理和磁盘调度</div></div></a></div><div><a href="/2021/05/23/操作系统/操作系统学习笔记-内存管理/" title="操作系统学习笔记-内存管理"><img class="cover" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/OperatingSystemscover1.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-05-23</div><div class="title">操作系统学习笔记-内存管理</div></div></a></div><div><a href="/2021/05/30/操作系统/操作系统学习笔记-单处理器调度/" title="操作系统学习笔记-单处理器调度"><img class="cover" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/OperatingSystemscover1.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-05-30</div><div class="title">操作系统学习笔记-单处理器调度</div></div></a></div><div><a href="/2021/05/04/操作系统/操作系统学习笔记-并发：死锁和饥饿/" title="操作系统学习笔记-并发：死锁和饥饿"><img class="cover" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/OperatingSystemscover1.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-05-04</div><div class="title">操作系统学习笔记-并发：死锁和饥饿</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div><div id="comment-switch"><span class="first-comment">Twikoo</span><span class="switch-btn"></span><span class="second-comment">Valine</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">花猪</div><div class="author-info__description">此站点就暂时停留在秋天了吧</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">86</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">20</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/CNhuazhu"><i class="fab fa-github"></i><span>我的github</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/CNhuazhu" rel="external nofollow noreferrer" target="_blank" title="Github"><i class="fab fa-github"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">花猪在此欢迎您光临小破站 (՞•Ꙫ•՞) <br><b>此站点已暂停更新！！！！</b><br><br>  <b><i>本站已部署至云服务器👇</i></b>：<a href="http://cnhuazhu.top">http://cnhuazhu.top</a> <br><br>  <b><i>github地址（暂停更新）</i></b>：<a target="_blank" rel="noopener external nofollow noreferrer" href="https://cnhuazhu.github.io/">https://cnhuazhu.github.io/</a> <br> <b><i>码云地址（暂停更新）</i></b>：<a target="_blank" rel="noopener external nofollow noreferrer" href="https://cnhuazhu.gitee.io">https://cnhuazhu.gitee.io</a> <br><br>  本站主题：Butterfly 3.7.8 <br> <img src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/pig.gif"></div><timing></timing></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">2.</span> <span class="toc-text">正文</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85-%E6%B6%88%E8%B4%B9%E8%80%85%E9%97%AE%E9%A2%98"><span class="toc-number">2.1.</span> <span class="toc-text">生产者-消费者问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%9A%E7%94%9F%E4%BA%A7%E8%80%85-%E5%A4%9A%E6%B6%88%E8%B4%B9%E8%80%85%E9%97%AE%E9%A2%98"><span class="toc-number">2.2.</span> <span class="toc-text">多生产者-多消费者问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%B8%E7%83%9F%E8%80%85%E9%97%AE%E9%A2%98"><span class="toc-number">2.3.</span> <span class="toc-text">吸烟者问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%BB%E8%80%85-%E5%86%99%E8%80%85%E9%97%AE%E9%A2%98"><span class="toc-number">2.4.</span> <span class="toc-text">读者-写者问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%93%B2%E5%AD%A6%E5%AE%B6%E8%BF%9B%E9%A4%90%E9%97%AE%E9%A2%98"><span class="toc-number">2.5.</span> <span class="toc-text">哲学家进餐问题</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">3.</span> <span class="toc-text">后记</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/11/02/NodeJS/%E5%BF%AB%E9%80%9F%E6%90%AD%E5%BB%BA%E4%B8%80%E4%B8%AAexpress%E6%9C%8D%E5%8A%A1%E5%99%A8/" title="快速搭建一个express服务器"><img src="https://gitee.com/CNhuazhu/tu-chuang1/raw/master/img-blog/Node_Express_cover.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="快速搭建一个express服务器"/></a><div class="content"><a class="title" href="/2021/11/02/NodeJS/%E5%BF%AB%E9%80%9F%E6%90%AD%E5%BB%BA%E4%B8%80%E4%B8%AAexpress%E6%9C%8D%E5%8A%A1%E5%99%A8/" title="快速搭建一个express服务器">快速搭建一个express服务器</a><time datetime="2021-11-02T00:39:53.000Z" title="发表于 2021-11-02 08:39:53">2021-11-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/10/28/%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%88Ubuntu%EF%BC%89/Nginx-uWSGI-Flask%E9%83%A8%E7%BD%B2%E8%87%B3Ubuntu/" title="Nginx+uWSGI+Flask部署至Ubuntu"><img src="https://gitee.com/CNhuazhu/tu-chuang1/raw/master/img-blog/Ubuntu_Server_cover.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx+uWSGI+Flask部署至Ubuntu"/></a><div class="content"><a class="title" href="/2021/10/28/%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%88Ubuntu%EF%BC%89/Nginx-uWSGI-Flask%E9%83%A8%E7%BD%B2%E8%87%B3Ubuntu/" title="Nginx+uWSGI+Flask部署至Ubuntu">Nginx+uWSGI+Flask部署至Ubuntu</a><time datetime="2021-10-28T03:01:09.000Z" title="发表于 2021-10-28 11:01:09">2021-10-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/10/18/Xftp%E4%BC%A0%E8%BE%93%E6%96%87%E4%BB%B6%E5%A4%B1%E8%B4%A5%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/" title="Xftp传输文件失败解决方案"><img src="https://gitee.com/CNhuazhu/tu-chuang1/raw/master/img-blog/Xftp_cover.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Xftp传输文件失败解决方案"/></a><div class="content"><a class="title" href="/2021/10/18/Xftp%E4%BC%A0%E8%BE%93%E6%96%87%E4%BB%B6%E5%A4%B1%E8%B4%A5%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/" title="Xftp传输文件失败解决方案">Xftp传输文件失败解决方案</a><time datetime="2021-10-18T09:50:16.000Z" title="发表于 2021-10-18 17:50:16">2021-10-18</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/10/13/%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%88Ubuntu%EF%BC%89/Hexo%E9%83%A8%E7%BD%B2%E8%87%B3%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%88%E7%BB%AD%EF%BC%89%E2%80%94%E2%80%94%E5%BB%BA%E7%AB%8B%E5%BC%95%E5%AF%BC%E9%A1%B5%E5%8F%8A%E5%88%86%E7%AB%99/" title="Hexo部署至服务器（续）——建立引导页及分站"><img src="https://gitee.com/CNhuazhu/tu-chuang1/raw/master/img-blog/Ubuntu_Server_cover.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Hexo部署至服务器（续）——建立引导页及分站"/></a><div class="content"><a class="title" href="/2021/10/13/%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%88Ubuntu%EF%BC%89/Hexo%E9%83%A8%E7%BD%B2%E8%87%B3%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%88%E7%BB%AD%EF%BC%89%E2%80%94%E2%80%94%E5%BB%BA%E7%AB%8B%E5%BC%95%E5%AF%BC%E9%A1%B5%E5%8F%8A%E5%88%86%E7%AB%99/" title="Hexo部署至服务器（续）——建立引导页及分站">Hexo部署至服务器（续）——建立引导页及分站</a><time datetime="2021-10-13T13:49:12.000Z" title="发表于 2021-10-13 21:49:12">2021-10-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/10/12/%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%88Ubuntu%EF%BC%89/Hexo%E9%83%A8%E7%BD%B2%E8%87%B3%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%88Ubuntu-20-04%EF%BC%89/" title="Hexo部署至服务器（Ubuntu 20.04）"><img src="https://gitee.com/CNhuazhu/tu-chuang1/raw/master/img-blog/Ubuntu_Server_cover.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Hexo部署至服务器（Ubuntu 20.04）"/></a><div class="content"><a class="title" href="/2021/10/12/%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%88Ubuntu%EF%BC%89/Hexo%E9%83%A8%E7%BD%B2%E8%87%B3%E6%9C%8D%E5%8A%A1%E5%99%A8%EF%BC%88Ubuntu-20-04%EF%BC%89/" title="Hexo部署至服务器（Ubuntu 20.04）">Hexo部署至服务器（Ubuntu 20.04）</a><time datetime="2021-10-12T07:13:40.000Z" title="发表于 2021-10-12 15:13:40">2021-10-12</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 By 花猪</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener external nofollow noreferrer" href="http://beian.miit.gov.cn/">蜀ICP备2021026748号</a><br>感谢光临<a href="http://cnhuazhu.top/" style="text-decoration:underline">小破站</a>,欢迎您提出宝贵的意见！</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script async="async">var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> {preloader.endLoading()})
setTimeout(function(){preloader.endLoading();}, 3000);</script></div><div class="js-pjax"><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex@latest/dist/katex.min.css"><script src="https://cdn.jsdelivr.net/npm/katex@latest/dist/contrib/copy-tex.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex@latest/dist/contrib/copy-tex.css"><script>(() => {
  document.querySelectorAll('#article-container span.katex-display').forEach(item => {
    btf.wrap(item, 'div', '', 'katex-wrap')
  })
})()</script><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'hexo-1g41404w9f800e94',
      region: ''
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'hexo-1g41404w9f800e94',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'VHoX95KsBQSMyzEc3TdpmBkF-MdYXbMMI',
      appKey: 'qnwObDMbgMEKnu1Gp8tk7PYJ',
      placeholder: '欢迎留下你的评论（昵称和邮箱为必填项）',
      avatar: 'monsterid',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-CN',
      recordIP: false,
      serverURLs: '',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: false,
      path: window.location.pathname,
      requiredFields: ["nick,mail"],
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Twikoo' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script><script src="https://pv.sohu.com/cityjson?ie=utf-8"></script><script src="/js/ip_content.js"></script><script src="/js/timing.js"></script><script src="https://cdn.jsdelivr.net/gh/xiabo2/CDN@latest/fishes.js"></script><script src="/js/footer.js"></script><script src="/js/ginkgo-leaf.js"></script><script id="canvas_nest" defer="defer" color="0,0,0" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div class="pjax-reload"><script async="async">var arr = document.getElementsByClassName('recent-post-item');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__fadeInLeft');
    arr[i].setAttribute('data-wow-duration', '600ms');
    arr[i].setAttribute('data-wow-delay', '200ms');
    arr[i].setAttribute('data-wow-offset', '100');
    arr[i].setAttribute('data-wow-iteration', '1');
  }</script><script async="async">var arr = document.getElementsByClassName('card-widget');
for(var i = 0;i<arr.length;i++){
    arr[i].classList.add('wow');
    arr[i].classList.add('animate__fadeInRightBig');
    arr[i].setAttribute('data-wow-duration', '');
    arr[i].setAttribute('data-wow-delay', '');
    arr[i].setAttribute('data-wow-offset', '');
    arr[i].setAttribute('data-wow-iteration', '');
  }</script></div><script defer="defer" src="https://cdn.jsdelivr.net/gh/graingert/wow@1.3.0/dist/wow.min.js"></script><script defer="defer" src="/js/wow_init.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
                        function butterfly_swiper_injector_config(){
                          var parent_div_git = document.getElementById('recent-posts');
                          var item_html = '<div class="recent-post-item" style="height: auto;width: 100%"><div class="blog-slider swiper-container-fade swiper-container-horizontal" id="swiper_container"><div class="blog-slider__wrp swiper-wrapper" style="transition-duration: 0ms;"><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" href="2021/03/28/Hexo魔改/Hexo魔改记录/" alt=""><img width="48" height="48" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/RotatingImage4.jpg" alt=""/></a><div class="blog-slider__content"><span class="blog-slider__code">2021-03-28</span><a class="blog-slider__title" href="2021/03/28/Hexo魔改/Hexo魔改记录/" alt="">Hexo魔改记录</a><div class="blog-slider__text">Hexo魔改记录</div><a class="blog-slider__button" href="2021/03/28/Hexo魔改/Hexo魔改记录/" alt="">详情   </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" href="2021/08/02/Vue/Vue学习笔记/" alt=""><img width="48" height="48" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/RotatingImage5.jpg" alt=""/></a><div class="blog-slider__content"><span class="blog-slider__code">2021-08-02</span><a class="blog-slider__title" href="2021/08/02/Vue/Vue学习笔记/" alt="">Vue学习笔记</a><div class="blog-slider__text">本文将介绍Vue的基础语法</div><a class="blog-slider__button" href="2021/08/02/Vue/Vue学习笔记/" alt="">详情   </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" href="2021/03/28/Java/Java学习记录/" alt=""><img width="48" height="48" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/RotatingImage8.jpg" alt=""/></a><div class="blog-slider__content"><span class="blog-slider__code">2021-03-28</span><a class="blog-slider__title" href="2021/03/28/Java/Java学习记录/" alt="">Java学习记录</a><div class="blog-slider__text">Java学习记录</div><a class="blog-slider__button" href="2021/03/28/Java/Java学习记录/" alt="">详情   </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" href="2021/03/28/操作系统/操作系统学习笔记/" alt=""><img width="48" height="48" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/RotatingImage7.jpg" alt=""/></a><div class="blog-slider__content"><span class="blog-slider__code">2021-03-28</span><a class="blog-slider__title" href="2021/03/28/操作系统/操作系统学习笔记/" alt="">操作系统学习笔记</a><div class="blog-slider__text">记录操作系统学习历程</div><a class="blog-slider__button" href="2021/03/28/操作系统/操作系统学习笔记/" alt="">详情   </a></div></div><div class="blog-slider__item swiper-slide" style="width: 750px; opacity: 1; transform: translate3d(0px, 0px, 0px); transition-duration: 0ms;"><a class="blog-slider__img" href="2021/03/28/计算机网络/计算机网络学习笔记/" alt=""><img width="48" height="48" src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/RotatingImage3.jpg" alt=""/></a><div class="blog-slider__content"><span class="blog-slider__code">2021-03-28</span><a class="blog-slider__title" href="2021/03/28/计算机网络/计算机网络学习笔记/" alt="">计算机网络学习笔记</a><div class="blog-slider__text">记录计算机网络学习历程</div><a class="blog-slider__button" href="2021/03/28/计算机网络/计算机网络学习笔记/" alt="">详情   </a></div></div></div><div class="blog-slider__pagination swiper-pagination-clickable swiper-pagination-bullets"></div></div></div>';
                          console.log('已挂载butterfly_swiper')
                          // parent_div_git.innerHTML=item_html+parent_div_git.innerHTML // 无报错，但不影响使用(支持pjax跳转)
                          parent_div_git.insertAdjacentHTML("afterbegin",item_html) // 有报错，但不影响使用(支持pjax跳转)
                          }
                        if( document.getElementById('recent-posts') && (location.pathname ==='all'|| 'all' ==='all')){
                        butterfly_swiper_injector_config()
                        }
                      </script><script defer src="https://cdn.jsdelivr.net/npm/hexo-butterfly-swiper/lib/swiper.min.js"></script><script defer data-pjax src="https://cdn.jsdelivr.net/npm/hexo-butterfly-swiper/lib/swiper_init.js"></script><!-- hexo injector body_end end --><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"hHeadPos":0.5,"vHeadPos":0.618,"jsonPath":"/live2dw/assets/assets/tororo.model.json"},"display":{"superSample":2,"width":200,"height":400,"position":"left","hOffset":0,"vOffset":-105},"mobile":{"show":false,"scale":0.5},"react":{"opacityDefault":0.7,"opacityOnHover":0.8},"log":false});</script></body></html>